package com.ella.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ella.entity.SysMenu;
import com.ella.entity.SysRole;
import com.ella.mapper.SysMenuMapper;
import com.ella.mapper.SysRoleMapper;
import com.ella.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 */
@Service
@Slf4j
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

	@Resource
	private SysRoleMapper roleMapper;

	@Resource
	private ISysMenuService sysMenuService;

	@Resource
	private SysMenuMapper sysMenuMapper;


	@Override
	public Set<String> getMenuPermissionByUserId(Long userId) {
		//先查询所有的角色ids
		List<Long> menuIds = roleMapper.selectMenuIdsByUserId(userId);
		//查询这些角色对应的权限信息
		List<SysMenu> sysMenus = sysMenuService.listByIds(menuIds);
		//取出角色关键字,然后封装
		Set<String> permission = new HashSet<>();
	   sysMenus.forEach(sysMenu -> {
		   String perms = sysMenu.getPerms();
		   if ( !"".equals(perms)  && perms != null){
			   permission.add(perms);
		   }
	   });
          return permission;
	}

	@Override
	public List<SysMenu> selectMenuTrees() {
		List<SysMenu> sysMenuList = sysMenuService.list();
		List<SysMenu> resultMenuList=new ArrayList<>();
		for(SysMenu sysMenu:sysMenuList){
			// 寻找子节点
			for(SysMenu e:sysMenuList){
				if(e.getParentId()==sysMenu.getMenuId()){
					sysMenu.getChildren().add(e);
				}
			}

			if(sysMenu.getParentId()==0L){
				resultMenuList.add(sysMenu);
			}
		}
		return resultMenuList;
	}
}
